package net.xdclass.controller;

import net.xdclass.req.ShortLinkAddReq;
import net.xdclass.req.ShortLinkDelReq;
import net.xdclass.req.ShortLinkPageReq;
import net.xdclass.req.ShortLinkUpdateReq;
import net.xdclass.service.ShortLinkService;
import net.xdclass.util.JsonData;
import net.xdclass.vo.ShortLinkVO;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lby
 */
@RestController
@RequestMapping("/api/link/v1")
public class ShortLinkController {

    @Autowired
    private ShortLinkService shortLinkService;

    @Value("${rpc.token}")
    private String rpcToken;

    /**
     * 新增短链
     * @param req
     * @return
     */
    @PostMapping("add")
    public JsonData createShortLink(@RequestBody ShortLinkAddReq req){
        return shortLinkService.createShortLink(req);
    }

    /**
     * 分页查询短链
     * @param req
     * @return
     */
    @GetMapping("page")
    public JsonData pageByGroupId(@RequestBody ShortLinkPageReq req) {
        Map<String, Object> result = shortLinkService.pageByGroupId(req);
        return JsonData.buildSuccess(result);
    }

    @PostMapping("del")
    public JsonData del(@RequestBody ShortLinkDelReq req) {
        return  shortLinkService.del(req);
    }

    @PostMapping("update")
    public JsonData update(@RequestBody ShortLinkUpdateReq req) {
        return shortLinkService.update(req);
    }

    @GetMapping("check")
    public JsonData check(@RequestParam("shortLinkCode") String shortLinkCode, HttpServletRequest request){

        String token = request.getHeader("rpc-token");

        if(rpcToken.equalsIgnoreCase(token)){

            ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);
            return shortLinkVO == null ? JsonData.buildError("短链不存在"):JsonData.buildSuccess();

        }else {
            return JsonData.buildError("非法访问");
        }

    }

}


